#include <iostream>
#include <queue>
#include <vector>
using namespace std;
#define int long long
typedef pair<int, int> PII;
queue<PII> q;
vector<vector<int>> nums(360, vector<int>(360, -1));
vector<vector<int>> flag(360, vector<int>(360, 0));
vector<vector<int>> f(360, vector<int>(360, 0));
int dx[4] = {0, -1, 0, 1};
int dy[4] = {1, 0, -1, 0};
signed main() {
    int M;
    cin >> M;
    for(int i = 0; i < M; i++) {
        int x, y, t;
        cin >> x >> y >> t;
        if(x == 0 && y == 0 && t == 0){
            cout << -1 << endl;
            return 0;
        }
        if (nums[x][y] == -1)
        {
            nums[x][y] = t;
        }
        else
        {
            nums[x][y] = min(nums[x][y], t);
        }
        for(int i = 0; i < 4; i++) {
            int m = x + dx[i], n = y + dy[i];
            if(m >= 0 && m <= 350 && n >= 0 && n <= 350) {
                if(nums[m][n] == -1) {
                    nums[m][n] = t;
                }else {
                    nums[m][n] = min(nums[m][n], t);
                }
            }
        }
    }
    q.push({0, 0});
    f[0][0] = 1;
    while(!q.empty()) {
        auto[a, b] = q.front();
        q.pop();
        for(int i = 0; i < 4; i++) {
            int row = a + dx[i], col = b + dy[i];
            if(row >= 0 && row <= 350 && col >= 0 && col <= 350 && (flag[a][b] + 1 < nums[row][col] || nums[row][col] == -1) && f[row][col] == 0) {
                flag[row][col] = flag[a][b] + 1;
                f[row][col] = 1;
                q.push({row, col});
                if(nums[row][col] == -1) {
                    cout << flag[row][col] << endl;
                    return 0;
                }
            }
        }
    }
    cout << -1 << endl;
    return 0;
}
    